﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProgrammingEducationSystem.Dto;
using ProgrammingEducationSystem.Models;
using ProgrammingEducationSystem.Services;
using ProgrammingEducationSystem.Services.IServices;
using ProgrammingEducationSystem.Tools;

//教室控制器==》只能管理员访问
namespace ProgrammingEducationSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ClassRoomsController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IClassRoomsService _classRoomsService;
        public ClassRoomsController(IMapper mapper, IClassRoomsService classRoomsService)
        {
            _mapper = mapper;
            _classRoomsService = classRoomsService;
        }
        //查询所有教室
        [HttpGet]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> SelectClassRoom()
        {
            var data = await _classRoomsService.AllAsync();
            return Ok(
                ApiResult.Success(data)
                );
        }
        //新增教室
        [HttpPost]
        [Authorize(AuthenticationSchemes = "Bearer")]
        [Authorize(Roles = "ADMIN")]
        public async Task<IActionResult> AddClassRooms(ClassRoomsForCreateDto classRoomsForCreateDto)
        {
            var classRoom = _mapper.Map<ClassRoom>(classRoomsForCreateDto);

            await _classRoomsService.AddAsync(classRoom);
            await _classRoomsService.SaveAsync();
            return Ok(
                ApiResult.Success(classRoom, "教室添加成功")
                );
        }
        //删除教室
        [HttpDelete ("{classRoomId}")]
        public async Task<IActionResult> DeleteClassRooms(Guid classRoomId) {
            var cr = _classRoomsService.GetById(classRoomId);
            if (cr == null) return BadRequest(
                ApiResult.Failure(classRoomId,"找不到该教室")
               );
            await _classRoomsService.DeleteAsync(classRoomId);
            await _classRoomsService.SaveAsync();
            return Ok(
                ApiResult.Success(null,"教室删除成功")
                );
        }
        //给教室改名
        [HttpPut]
        public async Task<IActionResult> UpdateClassRooms(ClassRoomForUpdateDto classRoomForUpdateDto) {
            var existingClassRoom = await _classRoomsService.GetById(classRoomForUpdateDto.Id);
            if (existingClassRoom == null) {
                return NotFound(ApiResult.Failure("教室不存在"));
            }
            _mapper.Map(classRoomForUpdateDto, existingClassRoom);
            _classRoomsService.UpdateAsync(existingClassRoom);
            await _classRoomsService.SaveAsync();
            return Ok(ApiResult.Success(existingClassRoom, "班级信息更新成功"));

        }
    }
}
